<template>
  <div class="main-container">
    <Carousel
      :pictures="pictures.slice(0, 5)"
      type="card"
      height="230px" />
    <!-- 推荐歌单 -->
    <PlayList
      title="你的歌单补给站"
      :playlists="playLists" />
    <!-- 推荐音乐 -->
    <div class="musiclist">
      <h4 class="title">推荐新音乐</h4>
      <div class="content">
        <div
          v-for="song in songLists"
          :key="song.id"
          class="song-recommend">
          <div
            @click="playSong(song)"
            class="mask">
            <span class="iconfont">&#xea82;</span>
          </div>
          <el-image
            :src="song.songImage"
            lazy
            class="left" />
          <div class="right">
            <p>{{ song.name }}</p>
            <p>{{ song.singer }}</p>
          </div>
        </div>
      </div>
    </div>
    <Mv
      title="最新mv"
      :mvs="mvLists"
      class="mv-list" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, inject, Ref, nextTick } from 'vue';
import { storeToRefs } from 'pinia';
import { getBanner, getPlayerList, getDeafultSong, getMv } from '../api/api';
import {
  setStorAge,
  getStorage,
  elMessage,
  getMusicUrls,
  getMusicInfos,
  getTheme,
} from '../utils/util';
import { elMessageType, storageType } from '../model/enum';
import { Playlist, Song, MV } from '../model';
import useFooterStore from '../store/footer';
import Carousel from '../components/Carousel.vue';
import PlayList from '../components/PlayList.vue';
import Mv from '../components/Mv.vue';

//获取主题相关设置
const color = getTheme().get('fontColor');
const colorBlack = getTheme().get('fontBlack');
const boxShadow = getTheme().get('shadow');

const footer = useFooterStore();
const { songList, current, isPlay, playProcess, playTime, songNum } =
  storeToRefs(footer);

//轮播图片
const pictures = reactive<string[]>(
  getStorage(storageType.SESSION, 'recommend-banners') || []
);
//推荐歌单
const playLists = reactive<Playlist[]>(
  getStorage(storageType.SESSION, 'recommend-playlists') || []
);
//推荐歌曲
const songLists = reactive<Song[]>(
  getStorage(storageType.SESSION, 'recommend-songlists') || []
);
//推荐mv
const mvLists = reactive<MV[]>(
  getStorage(storageType.SESSION, 'recommend-mvlists') || []
);

//第一次加载的动画
const first = inject<Ref<boolean>>('firstLoading');

//点击图片进行播放播放
const playSong = async (song: Song) => {
  if (song.available == '0' || song.available == '8') {
    const index = songList.value.findIndex((item) => item.id == song.id);
    if (index == -1) {
      if (current.value == 0) {
        if (isPlay) {
          isPlay.value = false;
        }
        playProcess.value = 0;
        playTime.value = 0;
        songList.value.unshift(song);
        await nextTick();
        isPlay.value = true;
      } else {
        songList.value.unshift(song);
        current.value = 0;
      }
    } else {
      if (current.value != index) {
        current.value = index;
      } else {
        isPlay.value = true;
      }
    }
  } else if ((song.available = '1')) {
    elMessage(elMessageType.INFO, '此歌曲为vip专属');
  } else if ((song.available = '10')) {
    elMessage(elMessageType.INFO, '此歌曲尚未拥有版权，请切换其它歌曲');
  }
};

//获取用户播放历史音乐的url
const getHistory = () => {
  if (songNum.value > 0) {
    const ids = songList.value.map((item) => item.id);
    getMusicUrls(ids.join(','), songList.value, 'userPlaylist');
  }
};

//缓存结果,后期需要删除
if (pictures.length == 0) {
  first!.value = true;
  //获取轮播图
  getBanner()
    .then((response: any) => {
      const { banners } = response;
      banners.forEach((banner: any) => {
        const { imageUrl } = banner;
        pictures.push(imageUrl);
      });
      setStorAge(storageType.SESSION, 'recommend-banners', pictures);
    })
    .catch((err: any) => {
      elMessage(elMessageType.ERROR, err.message);
    });

  //获取歌单信息
  getPlayerList()
    .then((response: any) => {
      const { playlists } = response;
      playlists.forEach((item: any) => {
        if (playLists.length < 10) {
          const {
            name,
            id,
            coverImgUrl,
            playCount,
            description,
            tags,
            creator,
          } = item;
          playLists.push({
            name,
            id,
            playCount,
            description,
            image: coverImgUrl,
            tag: tags,
            creator: {
              avatarUrl: creator.avatarUrl,
              nickname: creator.nickname,
            },
          });
        }
      });
      setStorAge(storageType.SESSION, 'recommend-playlists', playLists);
    })
    .catch((err: any) => {
      elMessage(elMessageType.ERROR, err.message);
    });
  //获取推荐的歌曲
  getDeafultSong(40)
    .then((response: any) => {
      const {
        data: { list },
      } = response;
      //获取歌曲的基本信息
      const ids: string[] = [];
      for (let item of list) {
        const { fee } = item.data;
        if (songLists.length < 10) {
          if (fee == '0' || fee == '8') {
            getMusicInfos(ids, songLists, item.data);
          }
        } else {
          break;
        }
      }
      getMusicUrls(ids.join(','), songLists, 'recommend-songlists');
      setTimeout(() => {
        first!.value = false;
      }, 500);
    })
    .catch((err: any) => {
      elMessage(elMessageType.ERROR, err.message);
    });

  //获取推荐的mv
  getMv(10, '内地')
    .then((response: any) => {
      const { data } = response;
      data.forEach((item: any) => {
        const { id, name, cover, playCount, artistName } = item;
        mvLists.push({
          id: id as string,
          name: name as string,
          image: cover as string,
          playCount: playCount as string,
          artist: artistName as string,
        });
      });
      setStorAge(storageType.SESSION, 'recommend-mvlists', mvLists);
    })
    .catch((err: any) => {
      elMessage(elMessageType.ERROR, err.message);
    });

  getHistory();
}
</script>

<style lang="less" scoped>
@font-color: v-bind(color);
@font-color-light-black: v-bind(colorBlack);
@shadow: v-bind(boxShadow);
@font-color-gray: #7b7b7b;
@font-color-green: #1ed2a9;

.main-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: auto;
  padding-top: 10px;

  .carousel {
    margin-bottom: 15px;
  }

  .musiclist {
    width: 80vw;
    margin-bottom: 20px;
    .title {
      font-weight: 520;
      font-size: 20px;
      letter-spacing: 1px;
      width: 80vw;
      color: @font-color;
      margin-bottom: 10px;
    }
    .content {
      display: flex;
      flex-wrap: wrap;

      .song-recommend {
        display: flex;
        margin: 10px 0 0;
        width: 40vw;
        position: relative;

        .mask {
          position: absolute;
          height: 50px;
          width: 50px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 10px;
          z-index: 2;
          display: flex;
          justify-content: center;
          align-items: center;
          transition: 0.5s;
          opacity: 0;
          &:hover {
            opacity: 1;
            transform: translateY(-5px);
          }
          &:hover + .left {
            transform: translateY(-5px);
          }

          span {
            color: rgba(255, 255, 255, 0.4);
            transition: 0.4s;
            &:hover {
              color: @font-color-green;
              cursor: pointer;
            }
          }
        }
        .left {
          cursor: pointer;
          width: 50px;
          height: 50px;
          object-fit: cover;
          border-radius: 10px;
          box-shadow: @shadow;
          transition: 0.5s;
        }
        .right {
          p {
            font-size: 12px;
            color: @font-color;
            margin-left: 10px;
            &:first-child {
              margin: 7px 0 2px 10px;
            }
            &:last-child {
              font-size: 10px;
              color: @font-color-gray;
            }
          }
        }
      }
    }
  }
}
</style>
